﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;

public partial class Business_Cisoft3G_ContactsManage_ContactsManage : WebUI.Page.RecursivePage
{

    //定义页数
    private static int pageNum = 0;
    private DataTable dt;
    public static ArrayList al = new ArrayList();

    #region 页面加载
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Initializtion(ddlUpperGroup, 0, 0, "顶级组", "CG_ContactGroupID", "CG_ParentID", "CG_GroupName", "CG_ContactGroup");
            //ltScript.Text = "<script type=\"text/javascript\" src=\"../../../js/Basic/BasicPage.js\"></script><script type=\"text/javascript\" src=\"../../../js/My97DatePicker/WdatePicker.js\"></script>";
            ltScript.Text = "<script type=\"text/javascript\" src=\"../../../js/My97DatePicker/WdatePicker.js\"></script>";
            Bind();
        }
    }
    #endregion

    #region 数据绑定
    private void gvitemBind(GridView gv)
    {
        GetList(gvitem, "", "");
    }
    #endregion

    #region 数据绑定
    /// <summary>
    /// 数据绑定
    /// </summary>
    private void Bind()
    {
        gvitemBind(gvitem);
    }
    #endregion 

    #region 翻页事件
    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {
        Bind();
    }
    #endregion

    #region 删除事件
    /// <summary>
    /// 删除事件
    /// </summary>
    protected void Button1_Click(object sender, EventArgs e)
    {
        bool result = true;
        string strError = string.Empty;
        Cisoft.Cisoft3G.BLL.ContactGroupBO bll = new Cisoft.Cisoft3G.BLL.ContactGroupBO();

        for (int i = 0; i < this.gvitem.Rows.Count; i++)
        {
            bool isChecked = ((CheckBox)gvitem.Rows[i].FindControl("chkSelect")).Checked;
            if (isChecked)//判断是否选择
            {
                int intID = Convert.ToInt32(((Label)gvitem.Rows[i].FindControl("LblID")).Text);
                //不能删除默认组
                if (intID == 1)
                {
                    PageError(ModalPopupExtender2, lblTS, btnBack_ts, "<h4>默认组无法删除！</h4>");
                    return;
                }
                
                //判断是否有下级组，有则无法删除
                if (bll.GetList(" CG_ParentID=" + intID).Tables[0].Rows.Count > 0)
                {
                    //string scriptStr = "location.replace(" + Server.HtmlEncode(" '../CustomRedrect.aspx?Type=False&Message=该组中还有下级组！如要删除该组，请先删除该组中的所有下级组。&Url=ContactsManage/ContactsGroupManage.aspx'") + ")";
                    //ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", scriptStr, true); 
                    PageError(ModalPopupExtender2, lblTS, btnBack_ts, "<h5>该组中还有下级组！如要删除该组，请先删除该组中的所有下级组。</h5>");
                    return;
                }

                LinkButton lbl_aShortName =  (LinkButton)gvitem.Rows[i].FindControl("lbl_aShortName");
                try
                {
                    bll.Delete(intID);
                    //删除联系人组时删除组中联系人
                    new Cisoft.Cisoft3G.BLL.ContactsBO().Delete(" CG_ContactGroupID_FK = " + intID);
                }
                catch (Exception ex)
                {
                    result = false;
                    strError += "通讯录组：'" + lbl_aShortName.Text + "'删除出现异常，请通知管理员，以下为出错提示信息：" + ex.Message.ToString();
                    continue;
                }
            }
        }
        if (result)
        {
            PageRight(ModalPopupExtender2, lblTS, btnBack_ts, "<h4>删除通讯录组记录成功！</h4>");
            Bind();
            //string scriptStr = "location.replace(" + Server.HtmlEncode(" '../CustomRedrect.aspx?Type=Success&Message=删除通讯录组记录成功！&Url=ContactsManage/ContactsGroupManage.aspx'") + ")";
            //ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", scriptStr, true); 

            //ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", "alert('删除成功！');", true);
            //gvitemBind(gvitem);
            //Initializtion(ddlUpperGroup, 0, 0, "顶级组", "CG_ContactGroupID", "CG_ParentID", "CG_GroupName", "CG_ContactGroup");
        }
        else
        {
            PageError(ModalPopupExtender2, lblTS, btnBack_ts, strError);
            Bind();
            //string scriptStr = "location.replace(" + Server.HtmlEncode(" '../CustomRedrect.aspx?Type=False&Message=" + strError + "&Url=ContactsManage/ContactsGroupManage.aspx'") + ")";
            //ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", scriptStr, true);
            //Initializtion(ddlUpperGroup, 0, 0, "顶级组", "CG_ContactGroupID", "CG_ParentID", "CG_GroupName", "CG_ContactGroup");
        }
    }
    #endregion

    #region 新增事件
    /// <summary>
    /// 新增事件
    /// fxc 201003101650
    /// </summary>
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        lblTitle.Text = "新增联系人组";
        txtGroupName.Text = "";
        txtOrder.Text = "";
        ddlUpperGroup.SelectedIndex = 0;
        //Response.Redirect("ContactsGroupAdd.aspx");
        btnConfirm.Visible = true;
        btnUpdate.Visible = false;
        LinkButton1_Click(sender, e);
    }
    //点击新增按钮
    protected void btnConfirm_Click(object sender, EventArgs e)
    {
        string strError = string.Empty;
        string groupName = txtGroupName.Text.Trim();
        int pid = int.Parse(ddlUpperGroup.SelectedValue);
        int order = int.Parse(txtOrder.Text.Trim());

        Cisoft.Cisoft3G.BLL.ContactGroupBO bll = new Cisoft.Cisoft3G.BLL.ContactGroupBO();
        Cisoft.Cisoft3G.Model.ContactGroupMO model = new Cisoft.Cisoft3G.Model.ContactGroupMO();

        model.CG_ContactGroupID = bll.GetMaxId();
        model.CG_GroupName = groupName;
        model.CG_Order = order;
        model.CG_ParentID = pid;

        try
        {
            bll.Add(model);
        }
        catch (Exception ex)
        {
            strError = "新增通讯录组失败！失败原因如下：" + ex.Message ;
        }
        if(!string.IsNullOrEmpty(strError))
        {
            PageError(ModalPopupExtender2, lblTS, btnBack_ts, strError);
            Bind();
            //string scriptStr = "location.replace(" + Server.HtmlEncode(" '../CustomRedrect.aspx?Type=False&Message=" + strError + "&Url=ContactsManage/ContactsGroupManage.aspx'") + ")";
            //ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", scriptStr, true);
            //Initializtion(ddlUpperGroup, 0, 0, "顶级组", "CG_ContactGroupID", "CG_ParentID", "CG_GroupName", "CG_ContactGroup");
        }
        else
        {
            PageError(ModalPopupExtender2, lblTS, btnBack_ts, "<h4>新增通讯录组成功！</h4>");
            Bind();
            //string scriptStr = "location.replace(" + Server.HtmlEncode(" '../CustomRedrect.aspx?Type=Success&Message=新增通讯录组成功！&Url=ContactsManage/ContactsGroupManage.aspx'") + ")";
            //ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", scriptStr, true); 

            //ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", "alert('新增成功！');", true);
            //txtGroupName.Text = "";
            //txtOrder.Text = "";
            //gvitemBind(gvitem);
            //Initializtion(ddlUpperGroup, 0, 0, "顶级组", "CG_ContactGroupID", "CG_ParentID", "CG_GroupName", "CG_ContactGroup");
        }

    }
    #endregion

    #region 修改事件
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        
        string strError = string.Empty;
        Cisoft.Cisoft3G.BLL.ContactGroupBO bll = new Cisoft.Cisoft3G.BLL.ContactGroupBO();
        Cisoft.Cisoft3G.Model.ContactGroupMO model = new Cisoft.Cisoft3G.Model.ContactGroupMO();

        model = bll.GetModel(int.Parse(lblGroupID.Text));
        if(model!=null)
        {
            model.CG_GroupName = txtGroupName.Text;
            model.CG_Order = int.Parse(txtOrder.Text);

            //判断是否为自己或自己的下级//如果要比较的ID是自己或自己的下级ID，返回真，如果不是，返回false
            if (IsRight(int.Parse(lblGroupID.Text),int.Parse(ddlUpperGroup.SelectedValue)))
            {
                ModalPopupExtender3.Show();
                lblSelectUpperGroup.Text = "<span style='color:red'>选择的上级组不能为自己或自己的下级组！</span>";
            }
            else
            {
                model.CG_ParentID = int.Parse(ddlUpperGroup.SelectedValue);
                try
                {
                    bll.Update(model);
                }
                catch (Exception ex)
                {
                    strError = "修改通讯录组失败！失败原因如下：" + ex.Message + "。";
                }
                if (!string.IsNullOrEmpty(strError))
                {
                    PageError(ModalPopupExtender2, lblTS, btnBack_ts, strError);
                    Bind();
                    //string scriptStr = "location.replace(" + Server.HtmlEncode(" '../CustomRedrect.aspx?Type=False&Message=" + strError + "&Url=ContactsManage/ContactsGroupManage.aspx'") + ")";
                    //ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", scriptStr, true);


                    //ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", "alert('修改通讯录组失败！失败原因如下：。');", true);
                    //txtGroupName.Text = "";
                    //txtOrder.Text = "";
                }
                else
                {
                    PageError(ModalPopupExtender2, lblTS, btnBack_ts, "<h4>修改通讯录组成功</h4>");
                    Bind();
                    //string scriptStr = "location.replace(" + Server.HtmlEncode(" '../CustomRedrect.aspx?Type=Success&Message=修改通讯录组成功！&Url=ContactsManage/ContactsGroupManage.aspx'") + ")";
                    //ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", scriptStr, true);

                    //ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "click", "alert('修改通讯录组成功！');", true);
                    //txtGroupName.Text = "";
                    //txtOrder.Text = "";
                    //gvitemBind(gvitem);
                }
            }
        }
    }
    #endregion

    #region gridview中的事件

    #region RowDataBound事件 protected void gvitem_RowDataBound(object sender, GridViewRowEventArgs e)
    /// <summary>
    /// RowDataBound事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gvitem_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //ID绑定
            Label LblID = (Label)e.Row.FindControl("LblID");
        }

        //鼠标在列表行中停留时的样式
        for (int i = -1; i < gvitem.Rows.Count; i++)
        {
            //首先判断是否是数据行
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //当鼠标停留时更改背景色
                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#B5C9DD'");
                //当鼠标移开时还原背景色
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
            }
        }
    }

    protected void gvitem_RowEditing(object sender, GridViewEditEventArgs e)
    {

    }
    #endregion

    #region gridview行命令
    protected void gvGroup_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        //展开
        if (e.CommandName == "Group_expended")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            GridViewRow row = this.gvitem.Rows[index];

            string flag = ((Label)row.FindControl("LblID")).Text;
            if (iIsout[int.Parse(flag)] == 0)
            {
                iIsout[int.Parse(flag)] = 1;
            }
            else
            {
                iIsout[int.Parse(flag)] = 0;
            }
            gvitemBind(gvitem);
        }
        //修改
        if (e.CommandName == "Edit")
        {
            lblTitle.Text = "修改联系人组";
            int id = int.Parse(e.CommandArgument.ToString());
            btnConfirm.Visible = false;
            btnUpdate.Visible = true;
            LinkButton1_Click(sender, e);

            Cisoft.Cisoft3G.BLL.ContactGroupBO bll = new Cisoft.Cisoft3G.BLL.ContactGroupBO();
            Cisoft.Cisoft3G.Model.ContactGroupMO model = new Cisoft.Cisoft3G.Model.ContactGroupMO();

            model = bll.GetModel(id);
            if (model != null)
            {
                lblGroupID.Text = model.CG_ContactGroupID.ToString();
                txtGroupName.Text = model.CG_GroupName;
                txtOrder.Text = model.CG_Order.ToString();
                ddlUpperGroup.SelectedValue = model.CG_ParentID.ToString();
            }
        }
    }

    protected void gvGroup_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton Lbtn_a = (LinkButton)e.Row.FindControl("lbl_aShortName");
            Lbtn_a.CommandArgument = e.Row.RowIndex.ToString();
        }
    }
    #endregion

    #region PageIndexChanging事件 protected void gvitem_PageIndexChanging(object sender, GridViewPageEventArgs e)
    /// <summary>
    /// PageIndexChanging事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gvitem_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvitem.PageIndex = e.NewPageIndex;
    }
    #endregion

    #endregion

    #region 显示隐藏层 void LinkButton1_Click
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        ModalPopupExtender3.Show();
    }
    #endregion

    #region 下拉框显示树型

    /// <summary>
    /// 初始化组合框级别（无限级栏目）
    /// </summary>
    /// <param name="dropList">组合框名称</param>
    /// <param name="iDepth">深度</param>
    /// <param name="iParentID">父类ID</param>
    public void Initializtion(DropDownList dropList, int iDepth, int iParentID, string strTip, string id, string pid, string name, string TableName)
    {
        dropList.Items.Clear();
        dropList.Items.Add(new ListItem(strTip, "0"));

        ShowColumns(dropList, iDepth, iParentID, id, pid, name, TableName);
    }

    /// <summary>
    /// 组合框显示所有级别（无限级级别）
    /// </summary>
    /// <param name="dropList">组合框名称</param>
    /// <param name="iDepth">深度</param>
    ///  <param name="iParentID">父类ID</param>int iParentID
    public void ShowColumns(DropDownList dropList, int iDepth, int iParentID, string id, string pid, string name, string tableName)
    {
        //定义变量
        int iCount = 0;
        int iSum = 0;
        string strGroupName = "";
        string strGroupID = "";
        DataSet ds = new DataSet();

        ds = new Cisoft.Cisoft3G.BLL.ContactGroupBO().GetList(" " + pid + "=" + iParentID + "  order by cg_order desc");

        iCount = ds.Tables[0].Rows.Count;

        if (iCount != 0)
        {
            //iSum深度处理
            iSum = iDepth + 1;

            for (int i = 0; i < iCount; i++)
            {
                if (i == (iCount - 1))
                {
                    strGroupName = replaceWord(GetDepth("┗" + ds.Tables[0].Rows[i][name].ToString(), iSum));
                    strGroupID = ds.Tables[0].Rows[i][id].ToString();

                    dropList.Items.Add(new ListItem(strGroupName, strGroupID));
                }
                else
                {
                    strGroupName = replaceWord(GetDepth("┗" + ds.Tables[0].Rows[i][name].ToString(), iSum));
                    strGroupID = ds.Tables[0].Rows[i][id].ToString();

                    dropList.Items.Add(new ListItem(strGroupName, ds.Tables[0].Rows[i][id].ToString()));
                }
                ShowColumns(dropList, iSum, Int32.Parse(ds.Tables[0].Rows[i][id].ToString()), id, pid, name, tableName);
            }
        }
    }

    /// <summary>
    /// 字符串插入"│"字符
    /// </summary>
    /// <param name="str">需要插入"│"的字符串</param>
    /// <param name="i">插入"│"字符串的索引位置</param>
    /// <returns></returns>
    private static string GetDepth(string strGroupName, int iCount)
    {
        for (int i = 1; i < iCount; i++)
        {
            strGroupName = strGroupName.Insert(0, "│");
        }

        return strGroupName;
    }

    /// <summary>
    /// 将指定字符串里的“&nbsp;”替换为空字符
    /// </summary>
    /// <param name="strText"></param>
    /// <returns></returns>
    private string replaceWord(string strText)
    {
        string outText = strText.Replace("&nbsp;", " ");
        return outText;
    }

    #endregion

    #region 判断一个ID是否为自己或者是自己的下级,是为true,不是为false bool IsRight(int id, int SelectValue)
    /// <summary>
    /// 判断一个ID是否为自己或者是自己的下级,是为true,不是为false
    /// </summary>
    /// <param name="id">自己的ID</param>
    /// <param name="SelectValue">需要比较的ID</param>
    private bool IsRight(int id, int SelectValue)
    {
        bool flag = false;
        //Function(id);
        Function(id);
        foreach (object ob in al)
        {
            if (SelectValue.ToString() == ob.ToString())
            {
                //如果要比较的ID是自己或自己的下级ID，返回真，如果不是，返回false
                flag = true;
                break;
            }
        }
        return flag;
    }
    #endregion

    #region 根据父ID递归获取该父ID下的所有子id void Function(int pid)
    /// <summary>
    /// 根据父ID递归获取该父ID下的所有子id
    /// </summary>
    /// <param name="pid">传入的父ID</param>
    public void Function(int pid)
    {
        al.Add(pid.ToString());
        DataSet ds = new Cisoft.Cisoft3G.BLL.ContactGroupBO().GetList(" CG_ParentID = " + pid + " ");
        if (ds.Tables[0].Rows.Count > 0)
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                al.Add(dr[0].ToString());
                Function(int.Parse(dr[0].ToString()));
            }
        }
    }
    #endregion

    #region 选择删除提示
    //显示选择删除
    protected void LinkButton2_Click(object sender, EventArgs e)
    {
        //if (!string.IsNullOrEmpty(hihDelete.Value) && hihDelete.Value == "false")
        //{
        //    lblTS.Text = "<br /><h4>请选择要删除的记录</h4><br />";
        //    btnConfirm2.Visible = true;
        //    btnCancel.Visible = false;
        //    ModalPopupExtender1.Show();
        //}
        //if (!string.IsNullOrEmpty(hihDelete.Value) && hihDelete.Value == "true")
        //{
        //    lblTS.Text = "<br /><h4>您确认删除吗？一旦删除，该组下的所有联系人都会被删除！</h4><br />";
        //    btnConfirm2.Visible = true;
        //    btnCancel.Visible = true;
        //    ModalPopupExtender1.Show();
        //}
        if (hihDelete.Value == "true")
        {
            Button1_Click(sender, e);
        }
    }
    protected void btnConfirm2_Click(object sender, EventArgs e)
    {
        if (hihDelete.Value == "true")
        {
            Button1_Click(sender, e);
        }
        else
        {

        }
    }
    #endregion

}

